package util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

@SuppressWarnings({"rawtypes", "unchecked"})
public class ClassUtil {
	private static Logger log = Logger.getLogger(ClassUtil.class);
	
	/**
	 * 获取实体对象中给定name的属性的值
	 * @param obj
	 * @param name
	 * @return
	 * @throws Exception
	 */
	public static Object getValue(Object obj, String name) throws Exception{
		Class cls = obj.getClass();
		Method method = cls.getDeclaredMethod(getGetter(name), new Class[]{});
		return method.invoke(obj, new Object[]{});
	}
	
	/**
	 * 获取实体对象中某个属性的get方法名
	 * @param fieldName
	 * @return
	 */
	private static String getGetter(String fieldName){
		return "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
	}
	
	/**
	 * 获取实体对象中某个属性的set方法名
	 * @param fieldName
	 * @return
	 */
	private static String getSetter(String fieldName){
		return "set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
	}
	
	/**
	 * 设置实体对象中给定name的属性的值
	 * @param obj
	 * @param name
	 * @param value
	 * @throws Exception
	 */
	public static void setValue(Object obj, String name, Object value) throws Exception{
		Class cls = obj.getClass();
		Field field = cls.getDeclaredField(name);
		String fieldName = field.getName();
	    Class fieldType = field.getType();
	    Method method = cls.getDeclaredMethod(getSetter(fieldName), fieldType);
	    method.invoke(obj, value);
	}
	
	/**
	 * 从request中解析出需要的对象
	 * @param request
	 * @param cls
	 * @return
	 */
	public static <T> T parseRequestAsEntity(HttpServletRequest request, Class cls) {
		Object result = null;
		try {
			result = cls.newInstance();
			Field[] fields = cls.getDeclaredFields();
			for (int i = 0; i < fields.length; i++) {
				Field field = fields[i];
				String fieldName = field.getName();
				Class fieldType = field.getType();
				cls.getDeclaredMethod(getSetter(fieldName), fieldType).invoke(result, request.getParameter(fieldName));
			}
		} catch (Exception e) {
			log.error("parsing " + cls.getSimpleName() + " from request encounted an error,the detailed error is " + e.getStackTrace());
			throw new RuntimeException("parsing " + cls.getSimpleName() + " from request encounted an error");
		}
		return (T) result;
	}
}
